package com.unhz.taigu.controller;

import com.unhz.generator.enums.EnumOderStatus;
import com.unhz.generator.enums.EnumStatus;
import com.unhz.generator.enums.EnumValid;
import com.unhz.generator.pojo.*;
import com.unhz.generator.utils.JsonResult;
import com.unhz.generator.utils.Page;
import com.unhz.generator.utils.PageSize;
import com.unhz.generator.vo.OrderVo;
import com.unhz.taigu.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: 王林恩
 * @Description: 订单表
 * @Date: Created in 上午 9:09 2018/1/29 0029
 * @Modified By:
 */
@Controller
@RequestMapping("/order")
public class OrderController{

    @Autowired
    private OrderService orderService;

    @Autowired
    private ContractService  contractService;

    @Autowired
    private InsoleService insoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private KeyService keyService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRolePermissionService sysRolePermissionService;



    /**
     * 分页查询
     * @param model
     * @param pageNo 页数
     * @param keywords 关键词
     * @return
     */
    @RequestMapping("/findAllOrder")
    public String findAllPermission(Model model,
                                    @RequestParam(value = "pageNo",defaultValue = "1",required = false)String pageNo,
                                    @RequestParam(value = "keywords",defaultValue = "",required = false)String keywords,
                                    @RequestParam(value = "adminId",defaultValue = "",required = false)Integer adminId,
                                    @RequestParam(value = "roleId",defaultValue = "",required = false)Integer roleId){
        //List<Permission> permissions = permissionService.selectAllPermission();
        Page<Order> page = orderService.selectPageOrder(pageNo, PageSize.pageSize,keywords,adminId,roleId);
        int count = sysRolePermissionService.selectOrderByroleId(roleId);
        model.addAttribute("count",count);
        model.addAttribute("page",page);
        model.addAttribute("keywords",keywords);
        return "order/index.jsp";
    }

    /**
     * 详情查询
     * @param model
     * @param orderId 订单id
     * @return
     */
    @RequestMapping("/findById")
    public String selectOrderById(Model model,
                                  @RequestParam(value = "orderId",defaultValue = "0",required = true ) Integer orderId){
        OrderVo order = orderService.findOrderById(orderId);
        List<Contract> contractList = contractService.findContractsByOrderId(orderId);
        model.addAttribute("order",order);
        model.addAttribute("contractList",contractList);
        return "order/details.jsp";
    }

    /**
     * 删除订单
     * @param orderId 订单id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult deleteOrderById(@RequestParam(value = "orderId",defaultValue = "0",required = true) Integer orderId){
        int res = 0;
        try{
            res = orderService.deleteOrderById(orderId);
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    /**
     * 跳转到修改订单页面
     * @return
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(Model model,@RequestParam(value = "orderId",defaultValue = "0",required = true) Integer orderId){
        Order order = orderService.selectOrderById(orderId);
        Integer userId = order.getUserId();
        Integer sampleId = order.getSampleId();
        User user = userService.selectUserById(userId);
        Insole insole = insoleService.selectByPrimaryKey(sampleId);
        List<Contract> contractList = contractService.findContractsByOrderId(orderId);
        List<Insole> insoleList = insoleService.selectAllInsoles();
        List<User> userList = userService.selectAllUser();
        model.addAttribute("order",order);
        model.addAttribute("insoleList",insoleList);
        model.addAttribute("contractList",contractList);
        model.addAttribute("userList",userList);
        model.addAttribute("insole",insole);
        model.addAttribute("user",user);
        model.addAttribute("date",new Date());
        return "order/update.jsp";
    }

    /**
     * 跳转到新增订单页面
     * @return
     */
    @RequestMapping("/toInsert")
    public String toInsert(Model model){
        List<Insole> insoleList = insoleService.selectAllInsoles();
        List<User> userList = userService.selectAllUser();
        model.addAttribute("insoleList",insoleList);
        model.addAttribute("userList",userList);
        return "order/add.jsp";
    }


    /**
     * 添加订单
     * @param order
     * @return
     */
    @RequestMapping("/insert")
    public String insert(Model model, Order order, Insole insole,
                         @RequestParam(value = "model",required = false) String insoleModel,
                         @RequestParam(value = "size",required = false) String [] size,
                         @RequestParam(value = "number",required = false) Integer []number,
                         @RequestParam(value = "adminId",required = false) Integer adminId,
                         @RequestParam(value = "roleId",required = false) Integer roleId){

        System.out.println("-------------------------"+size.length);
        for (int i=0;i<size.length;i++)
        {
            System.out.println("-------------------------"+size[i]);
        }



        Key key = keyService.selectKey();
        int orderKey = key.getOrderKey();
        if(orderKey==1){
            order.setValid(EnumValid.ENABLED.getIndex());
            order.setStatus(EnumStatus.PASS.getIndex());
        }else{
            order.setValid(EnumValid.FIRST_ENABLED.getIndex());
            order.setStatus(EnumStatus.CHECKING.getIndex());
        }
        Insole insoles = insoleService.selectInsoleByModel(insoleModel);
        Integer sampleId = insoles.getId();
        String midsole = insoles.getMidsole();
        String orderNoTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(System.currentTimeMillis());
        String orderNo = orderNoTime + insoleModel;
        order.setTradeName(order.getTradeName().replaceAll(" ",""));
        order.setWorkmanship(order.getWorkmanship().replaceAll(" ",""));
        order.setForeignModel(order.getForeignModel().replaceAll(" ",""));
        order.setOrderNo(orderNo);
        order.setSampleId(sampleId);
        order.setAdminId(adminId);
        System.out.println("----------------------------------"+number.length);
        int sum = 0;
            for (int i = 0; i < number.length; i++) {
                sum += number[i];
                if (number.length<8)
                {
                    int o=8-number.length;
                    System.out.println("----------------------------------"+o);
                    int[] iu=new int[o];
                    for (int p=0;p<o;p++)
                    {
                        sum += iu[p];
                    }
                }
            }


        order.setContractPrice(sum * order.getUnitPrice());
        order.setProcess(midsole);
        orderService.addOrder(order);
        Integer orderId = order.getId();
        Contract contract = null;
        for(int i=0;i<size.length;i++){
            contract = new Contract();
            contract.setOrderId(orderId);
            contract.setSize(size[i]);
            contract.setNumber(number[i]);
            contractService.addContract(contract);
        }
        return "redirect:/order/findAllOrder?adminId="+adminId+"&roleId="+roleId;
    }

    /**
     * 修改订单
     * @param order
     * @return
     */
    @RequestMapping("/update")
    public String update(Order order, Insole insole, User user,
                         @RequestParam(value = "model",required = false) String insoleModel,
                         @RequestParam(value = "adminName",required = false) String adminName,
                         @RequestParam(value = "size",required = false) String [] size,
                         @RequestParam(value = "number",required = false) int []number,
                         @RequestParam(value = "adminId",required = false) Integer adminId,
                         @RequestParam(value = "roleId",required = false) Integer roleId,
                         @RequestParam(value = "userId",required = false) Integer userId){
        String orderNoTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(System.currentTimeMillis());
        String orderNo = orderNoTime + insoleModel;
        //查询某个用户
        User users = userService.selectByPrimaryKey(userId);
        Insole insoles = insoleService.selectInsoleByModel(insoleModel);
        Integer sampleId = insoles.getId();
        order.setOrderNo(orderNo);
        order.setSampleId(sampleId);
        order.setStatus(EnumOderStatus.DOCKING.getIndex());
        order.setUpdateBy(adminName);
        order.setUpdateTime(new Date());
        order.setProcess(insoles.getMidsole());
        order.setUserId(userId);
        order.setAdminId(users.getAdminId());
        int sum = 0;
        for(int i=0;i<number.length;i++){
            sum += number[i];
        }
        order.setContractPrice(sum * order.getUnitPrice());
        orderService.updateOrder(order);
        int orderId = order.getId();
        contractService.deleteContractById(orderId);
        Contract contract = null;
        for(int i=0;i<size.length;i++){
            contract = new Contract();
            contract.setOrderId(orderId);
            contract.setSize(size[i]);
            contract.setNumber(Integer.valueOf(number[i]));
            contractService.addContract(contract);
        }
        return "redirect:/order/findAllOrder?adminId="+adminId+"&roleId="+roleId;
    }

    /**
     * 执行禁用或者启用
     * @param orderId
     * @param isenable
     * @return
     */
    @RequestMapping("/isenable")
    @ResponseBody
    @RequiresPermissions("order:isenable")
    public JsonResult isenable(@RequestParam("orderId")Integer orderId,
                               @RequestParam("isenable")Integer isenable,
                               @RequestParam("adminName")String adminName){
        String index = orderService.updateIsenable(orderId, isenable,adminName);
        if("success".equals(index)){
            return JsonResult.success("操作成功");
        }
        return JsonResult.failure("操作失败");
    }

    /**
     * 执行审核通过不通过
     * @param orderId
     * @param examine
     * @return
     */
    @RequestMapping("/examine")
    @ResponseBody
    @RequiresPermissions("order:examine")
    public JsonResult examine(@RequestParam("orderId")Integer orderId,
                              @RequestParam("examine")Integer examine,
                              @RequestParam("adminName")String adminName){
        String index = orderService.updateExamine(orderId, examine,adminName);
        if("success".equals(index)){
            return JsonResult.success("操作成功");
        }
        return JsonResult.failure("操作失败");
    }

    /**
     * 确定点击完成对接,后台状态修改为对接完成
     * @param orderId
     * @return
     */
    @RequestMapping("/finishDock")
    @ResponseBody
    public JsonResult finishDock(@RequestParam("orderId")Integer orderId){
        String index = orderService.finishDock(orderId);
        if("success".equals(index)){
            return JsonResult.success("操作成功");
        }
        return JsonResult.failure("操作失败");
    }

    /**
     * 一键审核
     * @return
     */
    @RequestMapping("/keyPass")
    @ResponseBody
    public JsonResult keyPass(){
        Order order = new Order();
        order.setValid(1);
        order.setStatus(2);
        orderService.keyPass(order);
        Key key = new Key();
        key.setId(1);
        key.setOrderKey(1);
        keyService.updateKey(key);
        return JsonResult.success("操作成功");
    }

    /**
     * 一键审核
     * @return
     */
    @RequestMapping("/noKeyPass")
    @ResponseBody
    public JsonResult noKeyPass(){
        Key key = new Key();
        key.setId(1);
        key.setOrderKey(0);
        keyService.updateKey(key);
        return JsonResult.success("操作成功");
    }

    /**
     * 查询一键审核状态
     * @return
     */
    @RequestMapping("/selectKey")
    @ResponseBody
    public Key selectKey(){
        Key key = keyService.selectKey();
        return key;
    }

}
